package com.acwebsitedesign.uRateDrugs.web;

import java.sql.SQLException;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.acwebsitedesign.uRateDrugs.domain.Drug;
import com.acwebsitedesign.uRateDrugs.domain.DrugService;

@Controller
@SessionAttributes("deleteDrug")
public class RemoveDrugController {
	
	@Autowired
	DrugService drugService;

	@RequestMapping("/removeDrug.html")
	public ModelAndView removeDrug(HttpSession session) {
		
		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		if (!(username.contentEquals("admin"))){
			ModelAndView mav = new ModelAndView("redirect:uRateDrugs-webapp/spring_security_login");
			return mav;
		}
	
	Drug deleteDrug = new Drug();
	ModelAndView mav = new ModelAndView("removeDrug");
	mav.addObject(deleteDrug);
	return mav;
	}
	
	@RequestMapping("/removeDrugByName.html")
	public ModelAndView removeDrugByName(@RequestParam String name,
			@ModelAttribute("removeDrug") Drug deleteDrug, BindingResult result, HttpSession session) throws SQLException {
	
		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		if (!(username.contentEquals("admin"))){
			ModelAndView mav = new ModelAndView("redirect:uRateDrugs-webapp/spring_security_login");
			return mav;
		}
		
		drugService.removeDrugByName(name);
		ModelAndView mav = new ModelAndView("DrugRemovalComplete");
		return mav;
	}
	
	@RequestMapping("/removeDrugByID.html")
	public ModelAndView removeDrugById(@RequestParam int id,
		@ModelAttribute("removeDrug") Drug deleteDrug, BindingResult result, HttpSession session) throws SQLException {

		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		if (!(username.contentEquals("admin"))){
			ModelAndView mav = new ModelAndView("redirect:uRateDrugs-webapp/spring_security_login");
			return mav;
		}
		
		drugService.removeDrugById(id);
		ModelAndView mav = new ModelAndView("DrugRemovalComplete");
		return mav;

	}
}